package reflection;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author liweimin
 * @date 2021/4/14 15:49
 * @description 动态代理测试类
 * @since
 */
public class DynamicProxyTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Calculator calculator = new CalculatorImpl();

        CalculatorHandler handler = new CalculatorHandler(calculator);

        Calculator instance = (Calculator) Proxy.newProxyInstance(Calculator.class.getClassLoader(), new Class[]{Calculator.class}, handler);

        instance.add(12, 43);
    }
}

interface Calculator {
    int add(int a, int b);
}

class CalculatorImpl implements Calculator {

    @Override
    public int add(int a, int b) {
        return a + b;
    }
}

class CalculatorHandler implements InvocationHandler {
    private Object object;

    public CalculatorHandler(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("proxy 是否是代理类对象 " + Proxy.isProxyClass(proxy.getClass()));
        System.out.println("-----------------------1-----------------------");
        Object invoke = method.invoke(object, args);
        System.out.println("操作后的返回对象：" + invoke);
        System.out.println("-----------------------2-----------------------");
        return invoke;
    }
}